import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
import * as api from './api';
import moment from 'moment';
import {uniqBy} from 'lodash';
export const GET_BRANDS_BEGIN = 'GET_BRANDS_BEGIN';
export const GET_BRANDS_SUCCESS = 'GET_BRANDS_SUCCESS';
export const GET_BRANDS_FAIL = 'GET_BRANDS_FAIL';
export const getBrandBegin = () => ({
    type: GET_BRANDS_BEGIN
});
export const getBrandSuccess = data => ({
    type: GET_BRANDS_SUCCESS,
    data
});
export const getBrandFail = () => ({
    type: GET_BRANDS_FAIL,
});

export const getBrands = condition => dispatch => {
    dispatch(getBrandBegin());
    return api.getBrands(condition).then(res => {
        if(res.ok)
            dispatch(getBrandSuccess(res.data));
        else
            dispatch(getBrandFail());
        return res.ok;
    });
};
/*==============================初始化API================================= */
export const GET_INIT_BEGIN = 'GET_INIT_BEGIN';
export const GET_INIT_SUCCESS = 'GET_INIT_SUCCESS';
export const GET_INIT_FAIL = 'GET_INIT_FAIL';
export const getInitDataBegin = () => ({
    type: GET_INIT_BEGIN
});
export const getInitDataSuccess = data => ({
    type: GET_INIT_SUCCESS,
    data,
});
export const getInitDataFail = () => ({
    type: GET_INIT_FAIL,
});
export const getInitData = (code = PAGE_CODE) => dispatch => {
    dispatch(getInitDataBegin());
    const init = api.initQuery().then(res => {
        if(res.ok)
            dispatch(getInitDataSuccess(res.data));
        else
            dispatch(getInitDataFail());
        return res.ok;
    });
    const brand = dispatch(getBrands());
    const permissions = getCurrentUserPagePermissionsApi(code).then(res => {
        if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    return Promise.all([init, permissions, brand]).then(values => values[0] && values[1] && values[2]);
};
/*==============================查询列表================================= */

export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';
export const getListBegin = () => ({
    type: GET_LIST_BEGIN
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition
});
export const getListFail = () => ({
    type: GET_LIST_FAIL,
}); //获取列表

export const getList = condition => dispatch => {
    const {invoiceNotificationTime, createTime, dealerCode, dealerName, ...props} = condition;
    if(invoiceNotificationTime && invoiceNotificationTime.length > 0) {
        props.beginInvoiceNotificationTime = moment(invoiceNotificationTime[0]).toISOString();
        props.endInvoiceNotificationTime = moment(invoiceNotificationTime[1]).toISOString();
    }
    if(createTime && createTime.length > 0) {
        props.beginCreateTime = moment(createTime[0]).toISOString();
        props.endCreateTime = moment(createTime[1]).toISOString();
    }
    dispatch(getListBegin());
    return api.getList(props).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
        return res.ok;
    });
}; //按钮搜索

export const querySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    dispatch(getList(condition));
}; //分页排序搜索

export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};

/*=============================提交================================= */
export const onClickSubmit = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.submitInfo(id, {
        rowVersion
    }).then(res => res.ok);
};
/*=============================开票通知================================= */
export const onClickInvoice = ids => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const conditions = ids.map(id => {
        const {rowVersion} = data.find(item => item.id === id);
        return {
            id,
            rowVersion
        };
    });
    return api.invoiceInfo({
        ids: conditions
    }).then(res => res.ok);
};

/*=============================作废================================= */
export const onClickAbandon = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.abandonInfo(id, {
        rowVersion
    }).then(res => res.ok);
};
/*=============================反结算================================= */
export const onClickReSettlement = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.reSettleInfo(id, {
        rowVersion
    }).then(res => res.ok);
};
/*=============================确认PI通过================================= */
export const onClickConfirmPI = id => (dispatch, getState) => {
    const {
        reportComment,
        rowVersion,
    } = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    return api.confirmPIInfo(id, {
        isConfirm: true,
        reportComment,
        rowVersion,
    });
};
/*=============================确认PI驳回================================= */
export const onClickNoConfirmPI = id => (dispatch, getState) => {
    const {
        reportComment,
        rowVersion,
    } = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    return api.confirmPIInfo(id, {
        isConfirm: false,
        reportComment,
        rowVersion,
    });
};
/*=============================上报财务================================= */
export const onClickFinance = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.financeInfo(id, {
        rowVersion
    }).then(res => res.ok);
};

/*==============================导出================================= */
export const exportData = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    const {invoiceNotificationTime, createTime, dealerCode, dealerName, isDesc, sortField, ...props} = condition;
    if(invoiceNotificationTime && invoiceNotificationTime.length > 0) {
        props.benginInvoiceNotificationTime = moment(invoiceNotificationTime[0]).toISOString();
        props.endInvoiceNotificationTime = moment(invoiceNotificationTime[1]).toISOString();
    }
    if(createTime && createTime.length > 0) {
        props.beginCreateTime = moment(createTime[0]).toISOString();
        props.endCreateTime = moment(createTime[1]).toISOString();
    }
    return api.exportInfo(props);
};

/*==============================台账导出================================= */
export const exports = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryCondition']).toJS();
    const {invoiceNotificationTime, createTime, ...props} = condition;
    if(invoiceNotificationTime && invoiceNotificationTime.length > 0) {
        props.benginInvoiceNotificationTime = moment(invoiceNotificationTime[0]).toISOString();
        props.endInvoiceNotificationTime = moment(invoiceNotificationTime[1]).toISOString();
    }
    if(createTime && createTime.length > 0) {
        props.beginCreateTime = moment(createTime[0]).toISOString();
        props.endCreateTime = moment(createTime[1]).toISOString();
    }
    return api.exports(props);
};

/*==============================查询action================================= */
//修改查询条件

export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
//重置查询条件

export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});


export const SAVE_SUBMIT_CONDITION = 'SAVE_SUBMIT_CONDITION';
export const saveSubmitCondition = (name, value) => ({
    type: SAVE_SUBMIT_CONDITION,
    name,
    value
});
/* =======================获取详情================================== */
export const GET_DETAIL_BEGIN = 'GET_DETAIL_BEGIN';
export const GET_DETAIL_SUCCESS = 'GET_DETAIL_SUCCESS';
export const GET_DETAIL_FAIL = 'GET_DETAIL_FAIL';
export const getDetailBegin = () => ({
    type: GET_DETAIL_BEGIN
});
export const getDetailSuccess = data => ({
    type: GET_DETAIL_SUCCESS,
    data
});
export const getDetailFail = () => ({
    type: GET_DETAIL_FAIL,
});

export const getDetail = id => dispatch => {
    dispatch(getDetailBegin());
    return api.getDetail(id).then(res => {
        if(res.ok)
            dispatch(getDetailSuccess(Object.assign({}, res.data, {
                details: res.data.details.map(item => Object.assign({}, item, {
                    repeatId: item.vin + item.partCodeRepeat + item.allTotalFee
                }))
            })));
        else
            dispatch(getDetailFail());
        return res.ok;
    });
};

export const getEditInit = id => (dispatch, getState) => {
    if(!id)
        return null;
    return dispatch(getDetail(id));
};

/* =======================详情页提交================================== */
export const onClickSubmitForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.submitInfo(id, {
        rowVersion
    });
};
/* =======================详情页开票通知================================== */
export const onClickInvoiceForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.invoiceInfo({
        ids: [{
            id,
            rowVersion
        }]
    });
};
/* =======================详情页作废================================== */
export const onClickAbandonForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.abandonInfo(id, {
        rowVersion
    });
};
/* =======================详情页反结算================================== */
export const onClickReSettleForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.reSettleInfo(id, {
        rowVersion
    });
};
/* =======================详情页上报财务================================== */
export const onClickFinanceForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.financeInfo(id, {
        rowVersion
    });
};

/*==============================清除数据================================= */
export const CLEAR_DATA = 'CLEAR_DATA';
export const clearData = () => ({
    type: CLEAR_DATA
});

/*=============================审核================================= */
export const onClickApprove = (id, data) => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    const {isApproved, ...props} = data;
    if(isApproved)
        return api.passInfo(id, {
            ...props,
            rowVersion
        }).then(res => res.ok);
    return api.rejectInfo(id, {
        ...props,
        rowVersion
    }).then(res => res.ok);
};
/*=============================多级审核================================= */
export const onClickMoreApprove = (id, data) => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    const {result, ...props} = data;
    if(result)
        return api.passApprove(id, {
            ...props,
            rowVersion
        }).then(res => res.ok);
    return api.rejectApprove(id, {
        ...props,
        rowVersion
    }).then(res => res.ok);
};

/*=============================上传PI================================= */
export const UPDATE_ATTACHMENTS = 'UPDATE_ATTACHMENTS';
export const updateAttachments = data => ({
    type: UPDATE_ATTACHMENTS,
    data: {
        fileId: data.id,
        fileName: data.fileName
    }
});

export const REMOVE_ATTACHMENTS = 'REMOVE_ATTACHMENTS';
export const removeAttachments = id => ({
    type: REMOVE_ATTACHMENTS,
    id
});

export const onClickUpPi = (id, data) => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.uppiInfo(id, {
        attachments: data,
        rowVersion
    }).then(res => res.ok);
};

export const SELECT_DEALER_QUERY = 'SELECT_DEALER_QUERY';
export const selectDealerQuery = data => ({
    type: SELECT_DEALER_QUERY,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});


export const CHANGE_BATCH = 'CHANGE_BATCH';
export const changeBatch = () => ({
    type: CHANGE_BATCH
});

import {transportType} from '../Enum';
export const onClickUpdate = id => (dispatch, getState) => {
    const {
        remark,
        rowVersion,
        department,
        details = [],
    } = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    return api.updateInfo(id, {
        businessType: transportType.整车,
        remark,
        rowVersion,
        department,
        deleteIds: uniqBy(details, 'claimIdBak').filter(item => item.isDelete).map(item => item.claimIdBak),
    });
};

export const onClickNew = rows => (dispatch, getState) => {
    const claimData = rows.map(item => {
        const {department, remark} = item;
        return {
            remark,
            department,
            details: uniqBy(item.details, 'claimId').map(p => ({
                id: p.claimId,
                rowVersion: p.rowVersion
            }))
        };
    });
    return api.addInfo({
        claims: claimData,
    });
};

export const UPDATE_DETAIL = 'UPDATE_DETAIL';
export const updateDetail = newDetails => ({
    type: UPDATE_DETAIL,
    newDetails
});

//获取历史数据列表
export const GET_HISTORY_LIST_BEGIN = 'GET_HISTORY_LIST_BEGIN';
export const GET_HISTORY_LIST_SUCCESS = 'GET_HISTORY_LIST_SUCCESS';
export const GET_HISTORY_LIST_FAIL = 'GET_HISTORY_LIST_FAIL';
export const getHistoryListBegin = () => ({
    type: GET_HISTORY_LIST_BEGIN
});
export const getHistoryListSuccess = (data, condition) => ({
    type: GET_HISTORY_LIST_SUCCESS,
    data,
    condition
});
export const getHistoryListFail = () => ({
    type: GET_HISTORY_LIST_FAIL,
});

//获取列表
export const getHistoryList = condition => dispatch => {
    dispatch(getHistoryListBegin());
    const {banlaceDate, dealerCode, dealerName, ...props} = condition;
    if(banlaceDate && banlaceDate.length > 0) {
        props.beginBanlaceDate = moment(banlaceDate[0]).toISOString();
        props.endBanlaceDate = moment(banlaceDate[1]).toISOString();
    }
    return api.getHistoryList(props).then(res => {
        if(res.ok)
            dispatch(getHistoryListSuccess(res.data, condition));
        else
            dispatch(getHistoryListFail());
        return res.ok;
    });
};

//按钮搜索历史
export const queryHistorySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'historyQueryCondition'])
        .toJS();
    return dispatch(getHistoryList(condition));
};

export const tableHistorySearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'historyQueryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    return dispatch(getHistoryList(condition));
};

//修改历史查询条件
export const SAVE_HISTORY_QUERY_CONDITION = 'SAVE_HISTORY_QUERY_CONDITION';
export const saveHistoryQueryCondition = (name, value) => ({
    type: SAVE_HISTORY_QUERY_CONDITION,
    name,
    value
});

//重置发票历史查询条件
export const RESET_HISTORY_QUERY_PANEL = 'RESET_HISTORY_QUERY_PANEL';
export const resetHistoryQueryPanel = () => ({
    type: RESET_HISTORY_QUERY_PANEL,
});

export const SELECT_HISTORY_DEALER_QUERY = 'SELECT_HISTORY_DEALER_QUERY';
export const selectHistoryDealer = data => ({
    type: SELECT_HISTORY_DEALER_QUERY,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});
